package com.lou.gulimail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lou.common.utils.PageUtils;
import com.lou.common.utils.Query;
import com.lou.gulimail.product.dao.CategoryDao;
import com.lou.gulimail.product.entity.CategoryEntity;
import com.lou.gulimail.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listAsTree() {
        List<CategoryEntity> list=baseMapper.selectList(null);
        List<CategoryEntity> rootCat = list.stream()
                .filter((categoryEntity) -> categoryEntity.getParentCid() == 0)
                .peek((menu)-> menu.setChildren(getChild(menu,list)))
                .sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0)))
                .collect(Collectors.toList());

        return rootCat;
    }

    @Override
    public void logicalRemove(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getAttrGroupPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        findCatelogPath(catelogId,path);
        Collections.reverse(path);
        return path.toArray(new Long[0]);
    }

    private void findCatelogPath(Long catelogId, List<Long> path){
        CategoryEntity byId = this.getById(catelogId);
        path.add(byId.getCatId());
        if(byId.getParentCid()!=0){
            findCatelogPath(byId.getParentCid(),path);
        }
    }

    //递归查找子菜单
    private List<CategoryEntity> getChild(CategoryEntity parent,List<CategoryEntity> all){
        List<CategoryEntity> child=all.stream()
                .filter((categoryEntity -> categoryEntity.getParentCid().equals(parent.getCatId())))
                //递归
                .peek(categoryEntity -> categoryEntity.setChildren(getChild(categoryEntity,all)))
                .sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0)))
                .collect(Collectors.toList());

        return child;
    }

}